package com.tuanzi.loan.web.bean.family;

import com.google.common.base.Functions;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.tuanzi.loan.business.entity.CurrentUser;
import com.tuanzi.loan.business.entity.LoginUser;
import com.tuanzi.loan.business.entity.family.CommSysCode;
import com.tuanzi.loan.business.entity.family.LoanAdvert;
import com.tuanzi.loan.business.entity.family.ProductInfo;
import com.tuanzi.loan.business.entity.family.ProductInfoStatus;
import com.tuanzi.loan.business.service.family.LoanAdvertService;
import com.tuanzi.loan.business.service.family.ProductInfoService;
import com.tuanzi.loan.core.aspect.Debug;
import com.tuanzi.loan.vo.view.family.LoanAdvertInfo;
import com.tuanzi.loan.web.configuration.JSFInfoBean;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.faces.bean.ViewScoped;
import java.sql.Time;
import java.text.SimpleDateFormat;
import java.util.*;

@Data
@Debug
@Slf4j
@Component
@ViewScoped
@EqualsAndHashCode(callSuper = true)
public class LoanAdvertInfoBean extends JSFInfoBean<LoanAdvertInfo> {

    @Autowired
    private LoanAdvertService loanAdvertService;

    @Autowired
    private ProductInfoService productInfoService;

    private List<CommSysCode> commSysCodes;
    private LoginUser loginUser;
    private List<ProductInfo> productInfos;

    @PostConstruct
    private void init() {
        commSysCodes = loanAdvertService.findAdvert();
        productInfos = productInfoService.listAllProductInfo();
        String id = getParamFromRequest("id");
        if (StringUtils.isNotBlank(id)) {
            LoanAdvert loanAdvert = loanAdvertService.findOne(Long.parseLong(id));
            $ = change(loanAdvert);
        } else {
            $ = new LoanAdvertInfo();
            changeStatusToAdd();
        }
    }
    public String onReturn(String url){
        return redirect(url,getParam());
    }

    public void onSave() {
        try {
            checkBaseMessage($);
        } catch (Exception e) {
            log.error(e.getMessage());
            addErrorMessage(e.getMessage());
            return;
        }

        List<LoanAdvert> loanAdverts = change($);
        if($.getId() != null){
            log.info("用户" + CurrentUser.get().getName() + "修改广告位前的数据为：" + new Gson().toJson(loanAdvertService.findOne($.getId())));
            log.info("用户" + CurrentUser.get().getName() + "修改广告位后的数据为：" + new Gson().toJson(loanAdverts));
        }
        for(LoanAdvert loanAdvert: loanAdverts){
            loanAdvertService.saveOrUpdate(loanAdvert);
        }
        $ = change(loanAdverts.get(0));
        changeStatusToView();
        addSuccessfullyMessage();
    }

    private void checkBaseMessage(LoanAdvertInfo info) throws Exception {

        if(CollectionUtils.isEmpty(info.getPrdId())){
            throw new RuntimeException("产品不能为空");
        }

        if(CollectionUtils.isEmpty(info.getChannel())){
            throw new RuntimeException("渠道不能为空");
        }

        if (info.getPlatform() == null) {
            throw new RuntimeException("平台不能为空");
        }

        if(CollectionUtils.isEmpty(info.getAdvertSpaces())){
            throw new RuntimeException("广告位不能为空");
        }

        if (info.getRedirectType() == null) {
            throw new RuntimeException("跳转类型不能为空");
        }

        if(CollectionUtils.isEmpty(info.getActivityIds())){
            throw new RuntimeException("活动名称不能为空");
        }


        if(info.getId() != null){  //修改模式
            if(info.getAdvertSpaces().size() > 1){
                throw new RuntimeException("修改模式下不能选择多个广告位");
            }
            if(info.getActivityIds().size() > 1){
                throw new RuntimeException("修改模式下不能选择多个活动名称");
            }
        }

    }


    private LoanAdvertInfo change(LoanAdvert loanAdvert) {

        LoanAdvertInfo record = new LoanAdvertInfo();
        record.setId(loanAdvert.getId());
        record.setActivityId(loanAdvert.getActivityId());
        record.setAdvertSpace(loanAdvert.getAdvertSpace());

        record.setAdvertSpaces(Lists.newArrayList(loanAdvert.getAdvertSpace()));
        record.setActivityIds(Lists.newArrayList(loanAdvert.getActivityId()));

        record.setChannel(Arrays.asList(loanAdvert.getChannel().split(",")));

        if (StringUtils.isNotBlank(loanAdvert.getExcludeChannel()))
            record.setExcludeChannel(Arrays.asList(loanAdvert.getExcludeChannel().split(",")));

        if(StringUtils.isNotBlank(loanAdvert.getExcludePrdId())){
            record.setExcludePrdId(Arrays.asList(loanAdvert.getExcludePrdId().split(",")));
        }

        record.setFixedStartTime(loanAdvert.getFixedStartTime());
        record.setFixedEndTime(loanAdvert.getFixedEndTime());
        record.setPlatform(loanAdvert.getPlatform());
        record.setPosition(loanAdvert.getPosition());
        if (loanAdvert.getProdId() != null || !loanAdvert.getProdId().equals(""))
            record.setPrdId(Arrays.asList(loanAdvert.getProdId().split(",")));
        record.setRedirectType(loanAdvert.getRedirectType() == null ? 0 : loanAdvert.getRedirectType());
        record.setStatus(loanAdvert.getStatus());
        if (loanAdvert.getTag() != null)
            record.setTag(Arrays.asList(loanAdvert.getTag().split(",")));
        record.setUpperLimit(loanAdvert.getUpperLimit());
        record.setRemark(loanAdvert.getRemark());
        record.setShowState(loanAdvert.getShowState());
        record.setSuggest(loanAdvert.getSuggest());
        record.setUtime(loanAdvert.getUtime());
        record.setCtime(loanAdvert.getCtime());
        record.setIsTimer(loanAdvert.getIsTimer());
        record.setStartTime(loanAdvert.getStarttime());
        record.setEndTime(loanAdvert.getEndtime());
        record.setOperator(loanAdvert.getOperator());
        return record;
    }

    private List<LoanAdvert> change(LoanAdvertInfo loanAdvertInfo) {

        List<LoanAdvert> loanAdverts = Lists.newArrayList();

        List<String> advertSpaces = Lists.transform(loanAdvertInfo.getAdvertSpaces(), Functions.toStringFunction());
        List<String> activityIds = Lists.transform(loanAdvertInfo.getActivityIds(), Functions.toStringFunction());

        for(String advertSpace: advertSpaces){

            for(String activityId: activityIds){

                //一个广告位下不能添加相同的贷款活动
                if(Objects.isNull(loanAdvertInfo.getId())){
                    if(CollectionUtils.isNotEmpty(loanAdvertService.findByAdvertSpaceAndActivityId(Integer.parseInt(advertSpace), Long.parseLong(activityId)))){
                        continue;
                    }
                }

                LoanAdvert record = new LoanAdvert();
                record.setId(loanAdvertInfo.getId());
                record.setPlatform(loanAdvertInfo.getPlatform());

                record.setAdvertSpace(Integer.parseInt(advertSpace));
                record.setActivityId(Long.parseLong(activityId));

                if (CollectionUtils.isEmpty(loanAdvertInfo.getPrdId())) {
                    loanAdvertInfo.setPrdId(Collections.singletonList("0"));
                }
                record.setProdId(Joiner.on(",").join(loanAdvertInfo.getPrdId()));

                if (CollectionUtils.isEmpty(loanAdvertInfo.getChannel())) {
                    record.setChannel("9999");
                } else {
                    record.setChannel(Joiner.on(",").join(loanAdvertInfo.getChannel()));
                }

                if(CollectionUtils.isNotEmpty(loanAdvertInfo.getExcludeChannel())){
                    record.setExcludeChannel(Joiner.on(",").join(loanAdvertInfo.getExcludeChannel()));
                }

                if(CollectionUtils.isNotEmpty(loanAdvertInfo.getExcludePrdId())){
                    record.setExcludePrdId(Joiner.on(",").join(loanAdvertInfo.getExcludePrdId()));
                }


                record.setRedirectType(loanAdvertInfo.getRedirectType());
                record.setPosition(loanAdvertInfo.getPosition());

                if (loanAdvertInfo.getTag() != null){
                    record.setTag(Joiner.on(",").join(loanAdvertInfo.getTag()));
                }

                if(loanAdvertInfo.getStartTime() != null){
                    record.setStarttime(loanAdvertInfo.getStartTime());
                }

                if(loanAdvertInfo.getEndTime() != null){
                    record.setEndtime(loanAdvertInfo.getEndTime());
                }

                SimpleDateFormat format = new SimpleDateFormat("HH:mm");
                if(loanAdvertInfo.getFixedStartTime() != null){
                    record.setFixedStartTime(new Time(loanAdvertInfo.getFixedStartTime().getTime()));
                }

                if(loanAdvertInfo.getFixedEndTime() != null){
                    record.setFixedEndTime(new Time(loanAdvertInfo.getFixedEndTime().getTime()));
                }

                record.setUpperLimit(loanAdvertInfo.getUpperLimit());
                record.setStatus(loanAdvertInfo.getStatus() == null ? 1 : loanAdvertInfo.getStatus());
                record.setShowState(1); //0表示逻辑删除，不展示
                Date day = new Date();
                record.setUtime(day);
                record.setCtime(loanAdvertInfo.getCtime() != null ? loanAdvertInfo.getCtime() : day);
                record.setIsTimer(loanAdvertInfo.getIsTimer());
                record.setOperator(CurrentUser.get().getName());

                loanAdverts.add(record);
            }

        }

        return loanAdverts;
    }
}
